package com.sun.temp.controller;

import com.sun.temp.bean.Material;
import com.sun.temp.bean.Qakansa;
import com.sun.temp.bean.Task;
import com.sun.temp.common.result.PageResult;
import com.sun.temp.common.result.Result;
import com.sun.temp.mapper.mapper3.QakansaDao;
import com.sun.temp.service.MaterialService;
import com.sun.temp.service.TaskService;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
public class ResultController {
    @Resource
    private TaskService taskService;

    @Resource
    private MaterialService materialService;

    @Resource
    private QakansaDao oracleTestDao;

    /**
     * 获取全部任务
     */
    @GetMapping("/getAllTasks")
    public Result getTasks() {
        return Result.success(taskService.queryAllTask());
    }

    /**
     * 任务分页
     */
    @GetMapping("/getTaskPage")
    public PageResult getTaskPage(@RequestParam Map<String, Object> params) {
        return PageResult.success(taskService.queryPage(params));
    }

    /**
     * 获取批次
     */
    @GetMapping("/findBatchByTaskId/{taskId}")
    public Result findBatchByTaskId(@PathVariable Integer taskId) {
        return Result.success(materialService.queryBatchByTaskId(taskId));
    }

    /**
     * 同步数据
     */
    @GetMapping("/syncData")
    public PageResult syncData(@RequestParam Map<String, Object> params) {

        // 获取今天的任务
        List<Task> tasks = taskService.queryTaskToday();

        // 如果task表没今天任务，就去oracle拿数据
        if (CollectionUtils.isEmpty(tasks)) {
            // oracle数据
            List<Qakansa> qakansas = oracleTestDao.getQAKANSA();
            // 生成今天的task任务
            Task task = new Task();
            task.setCreateTime(new Date());
            task.setStatus(1);
            taskService.insertTask(task);
            // 数据插入mysql-material,已经有数据了就不操作
            // List<Material> list = materialService.queryMaterialToday();
            // if (list == null || list.isEmpty()) {
            materialService.insertList(qakansas, task.getId());
            // }
        }
        return PageResult.success(taskService.queryPage(params));
    }

    /**
     * 今天的批次-用于任务开启
     */
    @GetMapping("/findBatchToday")
    public Result findBatchToday() {

        // 获取今天的任务
        List<Task> tasks = taskService.queryTaskToday();

        List<Material> list = null;
        if (!CollectionUtils.isEmpty(tasks)) {
            list = materialService.queryBatchByTaskId(tasks.get(0).getId());
        }
        return Result.success(list);
    }

    /**
     * 获取今天的数据
     * @return
     */
    @GetMapping("/findMaterialToday")
    public Result findMaterialToday() {
        List<Material> list = materialService.queryMaterialToday();
        return Result.success(list);
    }

    /**
     * 获取所有数据
     */
    @GetMapping("/getMaterial")
    public Result getMaterial() {
        return Result.success(materialService.queryMaterial());
    }

    /**
     * 获取对应日期的所有数据
     */
    @GetMapping("/getMaterialByDate")
    public Result getMaterialByDate(@RequestParam  String date) {
        return Result.success(materialService.queryMaterialByDate(date));
    }

    @GetMapping("/getMaterialByBatchAndGrade")
    public Result getMaterialByBatchAndGrade(@RequestParam String grade,@RequestParam String batch) {
        return Result.success(materialService.queryMaterialByGradeAndBatch(grade,batch));
    }

    @GetMapping("/saveTempData/{id}")
    public Result saveTempData(@PathVariable Integer id) {
        //materialService.saveMaterial(id);
        return Result.success();
    }

    /**
     * 调用python脚本传参
     *
     * @return
     * @throws IOException
     */
    @GetMapping("/callPython")
    public Result callPython(@RequestParam String batch, @RequestParam Integer grade) throws IOException {

        // Python脚本路径及参数
//        String pythonScript = "E:\\code\\zhuyoudianmu\\temp\\doc\\test.py";
        String pythonScript = "D:\\zydm\\py\\test.py";

        // 要传递给Python脚本的参数
        String arg1 = "batch:" + batch;
        String arg2 = "grade:" + grade;
        ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScript, arg1, arg2);
        Process process = processBuilder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder output = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            System.out.printf(line);
            output.append(line).append("\n");
        }

        int exitCode = -1;
        try {
            exitCode = process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (exitCode == 0) {
                System.out.println("Python脚本成功运行！输出结果为:\n" + output.toString());
            } else {
                System.err.println("Python脚本运行失败！退出码为:" + exitCode);
            }

            process.destroy();
        }
        return Result.success();
    }

    /**
     * 任务结果
     */
    @GetMapping("/getResultByTaskId/{id}")
    public Result getResultByTaskId(@PathVariable Integer id) {
        return Result.success(materialService.queryResultByTaskId(id));
    }
}
